package com.itheima.easy.handler.wechat;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.client.wechat.Config;
import com.itheima.easy.client.wechat.Factory;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradingConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.AppPayHandler;
import com.itheima.easy.client.wechat.response.AppPayResponse;
import com.itheima.easy.pojo.Trading;
import com.itheima.easy.utils.BeanConv;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.utils.ResponseChecker;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName WechatAppPayHandler.java
 * @Description 原生APP支付处理
 */
@Component
@Slf4j
public class WechatAppPayHandler extends WechatCommonPayHandler implements AppPayHandler {

    @Override
    public TradingVo appTrading(TradingVo tradingVo){
        //1、交易前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkCreateTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.CHECK_TRADING_FAIL);
        }
        //2、交易前置处理：幂等性处理
        beforePayHandler.idempotentCreateTrading(tradingVo);
        //3、获得微信客户端
        Config config = wechatPayConfig.config(tradingVo.getEnterpriseId());
        //4、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //5、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            AppPayResponse appPayResponse = factory.App().pay(
                String.valueOf(tradingVo.getTradingOrderNo()),
                String.valueOf(tradingVo.getTradingAmount()),
                tradingVo.getMemo());
            //6、检查网关响应结果
            boolean success = ResponseChecker.success(appPayResponse);
            //7、网关响应成功且appPayResponse有返回结果
            if (success&&!EmptyUtil.isNullOrEmpty(appPayResponse.getPrepayId())){
                tradingVo.setIsRefund(SuperConstant.NO);
                tradingVo.setPlaceOrderCode(appPayResponse.getCode());
                tradingVo.setPlaceOrderMsg(appPayResponse.getMessage());
                tradingVo.setPlaceOrderJson(appPayResponse.getPrepayId());
                tradingVo.setTradingState(TradingConstant.TRADE_WAIT_BUYER_PAY);
                Trading trading = BeanConv.toBean(tradingVo, Trading.class);
                tradingService.save(trading);
                return BeanConv.toBean(trading, TradingVo.class);
            }else {
                log.error("网关：微信APP统一下单：{},结果：{}", tradingVo.getTradingOrderNo(),
                        JSONObject.toJSONString(appPayResponse));
                throw new RuntimeException("网关：微信APP统一下单创建失败!");
            }
        } catch (Exception e) {
            log.error("微信APP统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("微信APP统一下单创建失败!");
        }
    }

}
